package com.dingup.provider.controller.student;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dingup.api.Util.JwtTokenUtil;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.Util.UuidUtil;
import com.dingup.api.base.HttpResContent;
import com.dingup.api.bean.page.PageData;
import com.dingup.api.bean.requestBean.student.StudentPageBean;
import com.dingup.api.enums.StudentCampusEnum;
import com.dingup.api.model.student.Student;
import com.dingup.api.model.sys.SysDept;
import com.dingup.api.model.sys.SysUser;
import com.dingup.provider.mapper.SysDeptMapper;
import com.dingup.provider.mapper.SysUserMapper;
import com.dingup.provider.service.permission.PermissionCacheService;
import com.dingup.provider.service.student.StudentService;
import com.dingup.provider.service.sys.SysDeptService;
import com.dingup.provider.service.sys.SysUserService;
import com.dingup.provider.util.StringUtil;
import com.suyeer.basic.util.BHttpResUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static com.dingup.api.base.BaseUtil.saveErrorMsgAndData;
import static com.dingup.api.base.BaseUtil.saveSuccessMsgAndData;

/**
 * Created by wancheng on 2018/8/2.
 */
@RestController()
@RequestMapping("/student")
public class StudentController {

    private static Logger logger = LoggerFactory.getLogger(StudentController.class);

    private final Integer DEFAULT_STUDENT_ROLE_ID = 2;

    private final String IF_SEE_STUDENT_PHONE_PERMISSION = "ifSeeStudentPhonePermission";

    @Autowired
    StudentService studentService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysDeptService sysDeptService;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysDeptMapper sysDeptMapper;
    @Autowired
    PermissionCacheService permissionCacheService;

    /**
     * 保存学生接口
     *
     * @param request
     * @param response
     * @param studentName
     * @param zoneNum
     * @param studentAccount
     * @param studentEmail
     */
    @RequestMapping(value = "/student_save.do",method = RequestMethod.POST)
    public void listAllUser(HttpServletRequest request, HttpServletResponse response,
                            String studentName,
                            String zoneNum,
                            String studentAccount,
                            String studentEmail) {
        HttpResContent<String> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("添加学生信息");
        try {
            String currentAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            String currentUserId = RedisUtils.getInstance().getUserId(currentAccount);
            if (!StringUtils.isEmpty(studentAccount) && sysUserService.selectUserIfExistByAccount(studentAccount)) {
                throw new Exception("手机号码已存在!");
            }
            if (!StringUtils.isEmpty(studentEmail) && sysUserService.selectUserIfExistByEmail(studentEmail)) {
                throw new Exception("邮箱已存在!");
            }
            if (StringUtils.isEmpty(studentEmail) && StringUtils.isEmpty(studentAccount)){
                throw new Exception("手机号和邮箱至少填写一个");
            }
            SysUser student = new SysUser();
            student.setUserId(UuidUtil.getUUID());
            student.setUserAccount(studentAccount);
            student.setUserName(studentName);
            student.setCreateUserId(currentUserId);
            student.setCreateTime(new Date());
            student.setMobile(zoneNum + "-" + studentAccount);
            student.setIfDelete(false);
            student.setIfSysUser(false);
            student.setIfFromDingtalk(false);
            student.setIfActive(false);
            student.setEmail(studentEmail);
            Integer[] roleId = {DEFAULT_STUDENT_ROLE_ID};
            saveSuccessMsgAndData(hrc, studentService.save(student, Arrays.asList(roleId)));
            logger.info("添加学生信息 student:{},deptId:{},role:{}", JSON.toJSONString(student), JSONArray.toJSONString(roleId));
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_current_user_dept.do",method = RequestMethod.POST)
    public void listAllUser(HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<List<SysDept>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取部门信息");
        try {
            String currentAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            String currentUserId = RedisUtils.getInstance().getUserId(currentAccount);
            List<Long> deptIds = RedisUtils.getInstance().getDataPermissionDept(currentAccount);
            List<SysDept> depts = sysDeptMapper.getDeptByDeptIdIn(deptIds);
            List<SysDept> allow = new ArrayList<>();
            depts.stream().forEach(
                    dept -> {
                        SysDept res = StudentCampusEnum.getAllowDept(dept);
                        if (!allow.contains(res)) {
                            allow.add(res);
                        }
                    }
            );
            saveSuccessMsgAndData(hrc, allow.stream().distinct().filter(dept -> {
                if (dept == null) {
                    return false;
                }
                return true;
            }).collect(Collectors.toList()));
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_student_msg_by_id.do",method = RequestMethod.POST)
    public void getStudentMsg(String studentId,
                              HttpServletRequest request, HttpServletResponse response) {
        HttpResContent<Student> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("根据ID获取学生的信息");
        try {
            String userId = RedisUtils.getInstance().getUserId(request);
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            Boolean ifSeeStudentPhone = false;
            if (userAccount != null){
                ifSeeStudentPhone = permissionCacheService.getPermission(userAccount,IF_SEE_STUDENT_PHONE_PERMISSION);
            }
            Student student = studentService.getStudentById(studentId);
            if (student == null) {
                throw new Exception("当前学生不存在");
            }
            if (userId == null || (!ifSeeStudentPhone && !userId.equals(student.getCreateUserId()))){
                String phone = student.getStudentAccount();
                String mobile = student.getMobile();
                student.setStudentAccount(StringUtil.phoneNumberFormat(phone));
                student.setMobile(StringUtil.phoneNumberFormat(mobile));
            }
            saveSuccessMsgAndData(hrc, student);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update_student.do",method = RequestMethod.POST)
    public void update(HttpServletRequest request, HttpServletResponse response,
                       String studentId,
                       String studentName,
                       String zoneNum,
                       String studentAccount,
                       String studentEmail) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("编辑学生");
        try {
            SysUser student = new SysUser();
            student.setUserId(studentId);
            student.setUserName(studentName);
            student.setEmail(studentEmail);
            if (!StringUtils.isEmpty(studentAccount)){
                student.setUserAccount(studentAccount);
                student.setMobile(zoneNum + "-" + studentAccount);
            }
            studentService.updateStudent(student, null);
            logger.info("编辑学生:{}",JSON.toJSONString(student) );
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            logger.error("编辑学生 error={}",e);
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/freeze_student.do",method = RequestMethod.POST)
    public void freeze(HttpServletRequest request, HttpServletResponse response,
                       String studentId) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("冻结学生");
        try {
            studentService.freezeStudent(studentId);
            logger.info("冻结学生:{}",studentId);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
    @RequestMapping(value = "/active_student.do",method = RequestMethod.POST)
    public void active(HttpServletRequest request, HttpServletResponse response,
                       String studentId,
                       String password) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("激活学生");
        try {
            saveSuccessMsgAndData(hrc, studentService.activeStudent(studentId,password));
            logger.info("激活学生:{},password:{}",studentId,password);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
    @RequestMapping(value = "/get_student_search.do",method = RequestMethod.POST)
    public void getStudentSearch(HttpServletRequest request, HttpServletResponse response,
                       String query,
                       Integer page,
                       Integer rows) {
        HttpResContent<Map<String, Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("搜索框查询学生账号");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            Boolean ifSeeStudentPhone = permissionCacheService.getPermission(userAccount,IF_SEE_STUDENT_PHONE_PERMISSION);
            String userId = RedisUtils.getInstance().getUserId(request);
            //获取当前用户的数据权限,登录时放置数据
            List<String> uIds = RedisUtils.getInstance().getDataPermissionEmployee(request);
            if (CollectionUtils.isEmpty(uIds)) {
                throw new Exception("当前登录人无此操作权限");
            }
            uIds.add(userId);
            Student student = new Student();
            student.setQuery(query);
            student.setPage(page);
            student.setRows(rows);
            PageData<Student> dataPage = studentService.getStudent(student, uIds);
            List<Student> students = dataPage.getData();
            students.stream().forEach(
                    s -> {
                        String mobile = s.getMobile();
                        String[] m = mobile.split("-");
                        if (m.length > 1){
                            s.setZoneNum(m[0]);
                            if (!userId.equals(s.getCreateUserId()) && !ifSeeStudentPhone){
                                s.setMobile(StringUtil.phoneNumberFormat(m[1]));
                                s.setStudentAccount(StringUtil.phoneNumberFormat(s.getStudentAccount()));
                            }else {
                                s.setMobile(m[1]);
                            }

                        }
                    }
            );
            Map<String, Object> res = new HashMap<>();
            res.put("page", page);
            res.put("rows", rows);
            res.put("data", students);
            res.put("total", dataPage.getTotal());
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
    @RequestMapping(value = "/get_student.do",method = RequestMethod.POST)
    public void select(HttpServletRequest request, HttpServletResponse response,
                       StudentPageBean studentPageBean) {
        HttpResContent<PageData<Student>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("筛选学生");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);

            String userId = RedisUtils.getInstance().getUserId(request);
            //获取当前用户的数据权限,登录时放置数据
            List<String> uIds = RedisUtils.getInstance().getDataPermissionEmployee(request);
            if (CollectionUtils.isEmpty(uIds)) {
                throw new Exception("当前登录人无此操作权限");
            }
            uIds.add(userId);
            PageData<Student> dataPage = studentService.getStudentByStudentPageBean(studentPageBean, uIds);
            Boolean ifSeeStudentPhone = permissionCacheService.getPermission(userAccount,IF_SEE_STUDENT_PHONE_PERMISSION);
            dataPage.getData().stream().forEach(
                    s -> {
                        String mobile = s.getMobile();
                        String[] m = mobile.split("-");
                        if (m.length > 1){
                            s.setZoneNum(m[0]);
                            if (!userId.equals(s.getCreateUserId()) && !ifSeeStudentPhone){
                                s.setMobile(StringUtil.phoneNumberFormat(m[1]));
                                s.setStudentAccount(StringUtil.phoneNumberFormat(s.getStudentAccount()));
                            }else {
                                s.setMobile(m[1]);
                            }

                        }
                    }
            );
            saveSuccessMsgAndData(hrc, dataPage);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
}
